package com.bilin.coin.network.builder;

import com.bilin.coin.ApiConstant;
import com.bilin.coin.network.RetrofitConfig;
import com.bilin.coin.network.api.RetrofitApi;
import com.bilin.coin.utils.GsonUtil;
import com.bilin.coin.utils.SharedPreferencesUtils;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by pundix002 on 2018/5/4.
 */

public class UpDateFileBuilder2 extends RetrofitRequestBuilder<String, UpDateFileBuilder2> {

     List<File> fileList = new LinkedList<>();
     Map<String,RequestBody> mapFile=new LinkedHashMap<>();


    @Override
    public Observable<String> build() {
        //MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        for (int i=0;i<fileList.size();i++) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), fileList.get(i));
            mapFile.put("file"+"\";filename=\""+fileList.get(i).getName(),requestBody);

        }

        String cookie = SharedPreferencesUtils.getInstance().getString("Cookie", "");
        Map<String, Object> mapCookie = GsonUtil.GsonToMaps(cookie);
        StringBuffer buffer = new StringBuffer();
        if (mapCookie != null) {
            for (String key : mapCookie.keySet()) {
                buffer.append(key).append("=").append(mapCookie.get(key)).append(";");
            }
        }
        headers.put("Cookie", buffer.toString() + "lang=" + SharedPreferencesUtils.getInstance().getString("lang", "cn") + ";Path=/");
        headers.put(ApiConstant.CSRF_TOKEN, SharedPreferencesUtils.getInstance().getString(ApiConstant.CSRF_TOKEN, ""));
        headers.put(ApiConstant.RegisterToken, SharedPreferencesUtils.getInstance().getString(ApiConstant.RegisterToken, ""));

        return RetrofitConfig
                .initRetrofitConfig()
                .baseUrl(baseUrl)
                .build().create(RetrofitApi.class)
                .upLoadFile(url, headers,params, mapFile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());

    }


    public UpDateFileBuilder2 params(Map<String, String> params) {
        this.params.putAll(params);
        return this;
    }


    public UpDateFileBuilder2 addParams(String key, String val) {
        params.put(key, val);
        return this;
    }

    public UpDateFileBuilder2 fileParams(List<File> fileParams) {
        this.fileList = fileParams;
        return this;
    }

    public UpDateFileBuilder2 addFileParams(File file) {
        fileList.add(file);
        return this;
    }
}
